package mysql

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"fmt"
	"errors"
	"encoding/json"
	dh "git.oschina.net/Ljohn/Base/lib/db"
	mysqlConf "git.oschina.net/Ljohn/Base/conf/mysql"
)
var db *sql.DB

func init(){
	var err error
	fmt.Println("正在开始初始化数据库.......")
	db,err = sql.Open("mysql",mysqlConf.UserName()+":"+mysqlConf.PWD()+"@tcp("+mysqlConf.Host()+":"+mysqlConf.Port()+")/"+mysqlConf.Database()+"?charset=utf8")
	if err != nil || db==nil{
		fmt.Println("初始化连接失败  ----------> :",err)
	}
	db.SetMaxOpenConns(2000)
	db.SetMaxIdleConns(1000)
}

func GetModel(sqlStr string,whereStr ...interface{})([]byte,error){
	if db==nil{
		return nil,errors.New("数据库连接失败")
	}
	stmt,err :=db.Prepare(sqlStr)
	if err!=nil{
		return nil,err
	}
	defer stmt.Close()

	fmt.Println(whereStr)

	rows,err :=stmt.Query(whereStr...)
	if err != nil {
		return nil,err
	}
	defer rows.Close()
	res,_ := dh.GetKeyValuesOne(rows)
	temp, err := json.Marshal(res)
	if err != nil {
		return nil,err
	}
	return temp,nil
}

func GetModelList(sqlStr string,whereStr ...interface{})([]byte,error){
	if db==nil{
		return nil,errors.New("数据库连接失败")
	}
	stmt,err :=db.Prepare(sqlStr)
	if err!=nil{
		return nil,err
	}
	defer stmt.Close()
	rows,err :=stmt.Query(whereStr...)
	if err != nil {
		return nil,err
	}
	defer rows.Close()
	res,_ := dh.GetKeyValuesAll(rows)
	temp, err := json.Marshal(res)
	if err != nil {
		return nil,err
	}
	return temp,nil
}

func ExecSQL(sqlStr string,whereStr ...interface{})(int64,error){
	if db==nil{
		return 0,errors.New("数据库连接失败")
	}
	stmt,err :=db.Prepare(sqlStr)
	if err!=nil{
		return 0,err
	}
	defer stmt.Close()
	res,err :=stmt.Exec(whereStr...)
	if err != nil {
		return 0,err
	}
	return res.LastInsertId()
}
